<?php if (!defined("_ECRIRE_INC_VERSION")) return;

include_spip('functions/pdk_common');

require_once(_DIR_PLUGIN_ECATALOGUE.'classes/class.GroupeModel.php');
require_once(_DIR_PLUGIN_PDK.'classes/models/PdkRubriqueModel.php');
require_once(_DIR_PLUGIN_ECATALOGUE.'classes/class.OptionModel.php');

function balise_ECATALOGUE_OPTION_FILTER_LINK($p) {

	return calculer_balise_dynamique($p,'ECATALOGUE_OPTION_FILTER_LINK', array());
}

function balise_ECATALOGUE_OPTION_FILTER_LINK_stat($args, $filtres) {
	return $args;
}

function balise_ECATALOGUE_OPTION_FILTER_LINK_dyn($id_rubrique = 0) {
    include_spip('functions/pdk_url');
    $rubriques = array( $id_rubrique );
    $rubrique_mdl = new PdkRubriqueModel();

    do { // get all parents id
        $rubrique = $rubrique_mdl->select_by_id($id_rubrique);
        $id_rubrique = $rubrique['id_parent'];
        $rubriques[] = $id_rubrique;
    } while ($id_rubrique != '0');
    $rubriques = array_unique($rubriques); //на всякий случай

    $options = array();

    //get required options
    $result = sql_select( array('id_option'),
                            array('spip_ecatalogue_articles_options as ao', 'spip_articles as a', 'spip_ecatalogue_products as p'),
                            array('id_rubrique in ('.implode(',', $rubriques).')', 'p.id_article=a.id_article',
                                    'a.id_article=ao.id_article', 'statut="publie"', 'quantity>0'),
                            array('id_option'));
    while ($row=sql_fetch($result)) {
        $options[] = $row['id_option'];
    }

    //get proprietes by options
    $result = sql_select( array('p.id_propriete', 'p.titre as p_titre', 'type', 'id_option', 'o.titre as o_titre'),
                            array('spip_ecatalogue_proprietes as p' , 'spip_ecatalogue_options as o'),
                            array('o.id_propriete=p.id_propriete', 'id_option in ('.implode(',', $options).')'),
                            '', // _orderby
                            array('p.titre') );
    while ($row=sql_fetch($result)) {
        if(isset($proprietes[$row['id_propriete']])) { //if exits add option to this propriete
            $proprietes[$row['id_propriete']]['options'][$row['id_option']] = $row['o_titre'];
        } else { //register new propriete
            $proprietes[$row['id_propriete']]=array( 'titre'=>$row['p_titre'], 'type'=>$row['type'],
                                                    'options'=>array($row['id_option']=>$row['o_titre']));
        }
    }

    return array('balise/ecatalogue_option_filter_link', 0,
		array('proprietes' => $proprietes)
    );
}

?>